﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Tasker.Composition.Events
{
    sealed class EventAggregator : IEventAggregator
    {
        private static List<Type> _types = new List<Type>();

        public void Raise<EventType>(EventType e) where EventType : EventBase
        {
            foreach (var type in _types.Where(t => typeof(IEventHandler<EventType>).IsAssignableFrom(t)))
                (Resolver.Resolve(type) as IEventHandler<EventType>).Handle(e);
        }

        public void RegisterEventHandlers()
        {
            var ass = Assembly.GetCallingAssembly();
            RegisterEventHandlersFromAssembly(ass);
        }

        public void RegisterEventHandlersFromAssembly(Assembly assembly)
        {
            foreach (var type in assembly.GetTypes())
            {
                if (type.IsClass && typeof(IEventHandler).IsAssignableFrom(type) && !_types.Contains(type))
                    _types.Add(type);
            }
            foreach (var a in assembly.GetReferencedAssemblies())
            {
                if (a.Name.StartsWith("Tasker."))
                    RegisterEventHandlersFromAssembly(Assembly.Load(a));
            }
        }
    }
}
